//
//  CMFileCache.m
//  LLP
//
//  Created by pan Shiyu on 12-10-14.
//  Copyright (c) 2012年 Porcellio. All rights reserved.
//

#import "CMFileCache.h"

static CMFileCache*  _myCMFileCache = nil;
@implementation CMFileCache

+ (CMFileCache*)shareFileCache{
    if (_myCMFileCache == nil) {
        _myCMFileCache = [[CMFileCache alloc]init];
    }
    return _myCMFileCache;
}

#pragma mark - private methods

- (NSString*) basePath{
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString* cachesPath = [paths objectAtIndex:0];
    return cachesPath;
}

- (BOOL)createPathIfNecessary:(NSString*)path {
    BOOL succeeded = YES;
    
    NSFileManager* fm = [NSFileManager defaultManager];
    if (![fm fileExistsAtPath:path]) {
        succeeded = [fm createDirectoryAtPath: path
                  withIntermediateDirectories: YES
                                   attributes: nil
                                        error: nil];
    }
    
    return succeeded;
}

#pragma mark - 

- (BOOL)hasData:(NSString*)fPath{
    NSFileManager* fm = [NSFileManager defaultManager];
    if ([fm fileExistsAtPath:fPath]) {
        NSData *data = [NSData dataWithContentsOfFile:fPath];
        return data.length>0? YES : NO;
    }
    return NO;
}
- (NSString*)filePathWithName:(NSString*)fName{
    return  [[self basePath] stringByAppendingPathComponent:fName];
}

- (void)saveFile:(NSData*)fData withPath:(NSString*)fPath{
    NSFileManager* fm = [NSFileManager defaultManager];
    if (fData) {
        [fm createFileAtPath:fPath contents:fData attributes:nil];
    }else {
        [fm removeItemAtPath:fPath error:nil];
    }
}
- (NSData*)fileDataByPath:(NSString*)fPath{
    NSData *data = [NSData dataWithContentsOfFile:fPath];
    return data.length>0? data : nil;
}
- (void)removeFileByPath:(NSString*)fPath{
    NSFileManager* fm = [NSFileManager defaultManager];
    if ([fm fileExistsAtPath:fPath]) {
        [fm removeItemAtPath:fPath error:nil];
    }
}

- (void)removeAll{
    
    NSFileManager* fm = [NSFileManager defaultManager];
    [fm removeItemAtPath:[self basePath] error:nil];
}
- (float)cacheSize{
    return 0;
}

@end
